// const paymentUrl = require('../../config').paymentUrl
var app = getApp();
const $ = require('../../utils/utils');
const config = require('../../config');
const paymentUrl = app.host_url + 'charge/payment';
const wallet = require("../../manager/walletManager");

Page({
    data: {
        amountList: [],
        curSelected: '6666',
        chargeCode: '0',
        chargeAmount:'0',
        coupon_amount:'无可用',
        coupon_discount:'',
        coupon_id:null,
        coupon_type:'',
        pay_amount:null,
        channel: 1,
        despoit: "",
        payid: "",
        showCancel: false,
        isChooseAmount: false,
        isPaySuccess: false,
        path: "",
        showCoupon: false,
        couponList: [],
        couponListNor: []
    },

    /*********************LifeCycle ***********************/
    onLoad: function (options) {
        wx.removeStorageSync("scanIsFromLogin")
        console.log(`#request_payment_onLoad()${JSON.stringify(options)}  用户是否提交押金:${wx.getStorageSync('deposit_flag')} `)
        if (options.path) {
            this.setData({
                path: options.path
            });
        }

        this.getChargeAmountList();
    },

    onShow: function () {
        if (getCurrentPages().length == 1) {
            this.setData({ showCancel: true });
        }
    },

    /************************** Methods *****************/

    toVipPage: function () {
        $.goto(config.page.vip)
    },

    getChargeAmountList: function () {

        let data = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken')
        }

        let url = $.getUrl(config.getChargeAmountList, data)
        $.get(url).then(data => {
            this.setData({
                amountList: data.items
            });
        })
    },

    despoit_webview: function () {
        app.globalData.webview = {
            url: config.licenseUrl,
            title: '用户协议'
        };
        $.goto(config.page.webview);
    },

    selectAmount: function (e) {
        console.log(e);
        var self = this;
        var code;
        var chargeAmount;
        if (e.target.dataset.id == this.data.curSelected) {
            code = 0;
            chargeAmount = 0;
        } else {
            code = e.target.dataset.code
            chargeAmount = e.target.dataset.amount
        }
        var dataId = e.target.dataset.id == this.data.curSelected ? -1 : e.target.dataset.id;
        
        this.setData({
            curSelected: dataId,
        });

        if (dataId < 0){
            return
        }

        let item = this.data.amountList[dataId];
        this.setData({
            chargeAmount: chargeAmount,
            chargeCode: code,
            coupon_amount: item.coupon_id == null ? '无可用' : item.coupon_amount,
            coupon_discount: item.coupon_id == null ? '' : item.coupon_discount,
            coupon_id: item.coupon_id,
            coupon_type: item.coupon_id == null ? '' : item.coupon_type,
            pay_amount: item.pay_amount
        })
    },

    requestPayment: function () {

        var that = this;
        if (that.data.chargeAmount == 0) {
            wx.showToast({
                title: '请选择充值金额',
                icon: 'none',
                duration: 2000
            });
            return;
        }
        let data = {
            charge_code: that.data.chargeCode,
            charge_type: '1',
            coupon_id: that.data.coupon_id,
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
            pay_amount: that.data.pay_amount
        }




        var amount = that.data.chargeAmount;
        wx.showToast({
            title: '支付请求...',
            icon: 'loading',
            success: function (res) {
                let data = {
                    charge_code: that.data.chargeCode,
                    charge_type: '1',
                    coupon_id: that.data.coupon_id,
                    userid: wx.getStorageSync('userid'),
                    usertoken: wx.getStorageSync('usertoken'),
                    pay_amount: that.data.pay_amount
                }
                let url = config.paymentV2
                $.post(url, data).then(data => {
                    wx.hideLoading();
                    var payid = data.detail.prepayId;
                    var payargs = data.payargs;
                    if (data.code == '0') {
                        if (data.detail.payFlag == 1){
                            wx.requestPayment({
                                timeStamp: data.detail.timeStamp,
                                nonceStr: data.detail.nonceStr,
                                package: data.detail.pkg,
                                signType: data.detail.signType,
                                paySign: data.detail.sign,
                                'success': function (res) {
                                    if (that.data.path == "index") {
                                        $.goto(config.page.topupSuccess + "?path=index", true)
                                    } else {
                                        $.goto(config.page.topupSuccess, true)
                                    }
                                },
                                'fail': function (res) {
                                    let data = {
                                        userid: wx.getStorageSync('userid'),
                                        usertoken: wx.getStorageSync('usertoken'),
                                    }
                                    let url = config.cancelPayment
                                    $.post(url, data).then(data => {
                                    })

                                    //支付失败跳转页面
                                    wx.showToast({
                                        title: '支付失败',
                                        icon: 'none',
                                        duration: 2000
                                    });

                                }
                            });
                        }else{
                            if (that.data.path == "index") {
                                $.goto(config.page.topupSuccess + "?path=index", true)
                            } else {
                                $.goto(config.page.topupSuccess, true)
                            }
                        }
                        
                    } else {
                        wx.showModal({
                            title: '支付错误！',
                            content: data.message,
                        })
                        // reject()
                    }
                })
            }
        })

        // wallet.topupAction(amount, 1).then(data => {
            // if (that.data.path == "index") {
            //     $.goto(config.page.topupSuccess + "?path=index", true)
            // } else {
            //     $.goto(config.page.topupSuccess, true)
            // }
        // }).catch(error => {
        //     console.log(error)
        //     $.showToast("充值失败")
        // })
    },

    cancelPayment: function () {
        $.goto(config.page.index, true);
    },


    tapBackBtn: function () {

        if (this.data.path === "index") {
            wx.setStorageSync("scanIsFromLogin", true)
            app.scanCode()
        }

        wx.navigateBack({
        })

    },

    confirmCoupon: function () {
        wx.showModal({
            title: '提示',
            content: '当前没有可用的优惠券',
            showCancel: false,
            confirmColor: '#FF3B30',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定')
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },

    // 查看优惠券列表
    showCouponList: function () {
        this.setData({
            couponList: [],
            couponListNor: []
        })
        let data = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
            oper: '0',
            amount: this.data.chargeCode
        }
        let url = $.getUrl(config.getCouponList, data)
        $.get(url).then(data => {
            console.log('#request_showCouponList', data)
            let list = data.items
            let couponList = this.data.couponList
            let couponListNor = this.data.couponListNor
            for (var i = 0; i < list.length; i++) {
                if (list[i].avaiable == 1) {
                    couponList.push(list[i])
                } else {
                    couponListNor.push(list[i])
                }
            }
            this.setData({
                showCoupon: true,
                couponList: couponList,
                couponListNor: couponListNor
            })
        })

    },

    // 选择优惠券
    selCoupon:function(e){
        console.log('selCoupon-----',e)
        let couponId = e.currentTarget.dataset.id
        if (this.data.coupon_id == couponId) {
            this.setData({
                coupon_id: ''
            })
        } else {
            this.setData({
                coupon_id: couponId
            })
        }
        this.calcPayAmount(this.data.coupon_id)
    },

    // 计算金额
    calcPayAmount: function (couponId){
        let data = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken'),
            oper: '0',
            coupon_id: couponId,
            amount: this.data.chargeCode,
        }
        $.post(config.calcPayAmount, data).then(data => {
            console.log('#request_selCoupon_data--', data)
            if (data.code == 0) {
                let pay_amount = ''
                if (data.detail.coupon_id == null) {
                    pay_amount = this.data.chargeCode
                } else {
                    pay_amount = data.detail.pay_amount
                }
                this.setData({
                    coupon_discount: data.detail.coupon_discount,
                    coupon_id: data.detail.coupon_id,
                    coupon_type: data.detail.coupon_type,
                    pay_amount: pay_amount,
                    coupon_amount: data.detail.coupon_amount,
                })
            }

        })
    },

    shut_shadow: function () {
        this.setData({
            showCoupon: false
        })
    },


})
